package com.winai.launcher.base;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Looper;
import android.os.PowerManager;
import android.provider.Settings;
import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.ks.projectbasictools.ActivityCollector;
import com.ks.projectbasictools.AppManager;
import com.ks.projectbasictools.utils.LogUtils;
import com.taobao.sophix.SophixManager;
import com.winai.launcher.R;
import com.winai.launcher.SophixStubApplication;
import com.winai.launcher.constant.Constant;
import com.winai.launcher.override.MyOrientationListener;
import com.winai.launcher.override.UpdateCountTimer;
import com.winai.launcher.override.dialog_global.GlobalDialog;

import java.io.Serializable;
import java.util.Map;

public class BaseActivity extends AppCompatActivity {
    private CountDownTimer countDownTimer;//15秒倒计时重启设备
    private CountDownTimer dayCountTimer;//一天倒计时重新检查更新
    private GlobalDialog tipDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setStatusBar(true, true, R.color.colorTransparent);
        super.onCreate(savedInstanceState);
        // 隐藏标题栏
        if (getSupportActionBar() != null)
            getSupportActionBar().hide();
        //添加到Activity管理
        ActivityCollector.addActivity(this, getClass());
        //将Activity实例添加到AppManager的堆栈
        AppManager.getAppManager().addActivity(this);

        getWindow().setBackgroundDrawable(null);
        init();
    }

    private void init() {
        /*隐藏系统锁屏*/
//        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
//        getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
        /*检查补丁，系统版本更新——按天倒计时，重启设备之后只需调用一次*/
        LogUtils.i("Constant.checkUpdate = " + Constant.checkUpdate);
        if (Constant.checkUpdate) {
            Constant.checkUpdate = false;
            //TODO 更换账号之后放开
//            checkUpdate();
        }
        /*屏幕旋转*/
        MyOrientationListener myOrientationListener = new MyOrientationListener(this);
        boolean autoRotateOn = (android.provider.Settings.System.getInt(getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0) == 1);
        //检查系统是否开启自动旋转
        if (autoRotateOn) {
            myOrientationListener.enable();
        }

        initCountDownTimer();
    }

    private void initCountDownTimer() {
        /*15秒倒计时重启设备*/
        countDownTimer = new CountDownTimer(15000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                String ss = String.format(BaseActivity.this.getResources().getString(R.string.confirmTimer), millisUntilFinished / 1000);
                tipDialog.setConfirmText(ss);
            }
            @Override
            public void onFinish() {
                tipDialog.dismiss();
                reboot(BaseActivity.this.getApplicationContext());
            }
        };
        dayCountTimer = new CountDownTimer(Constant.DAY, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {}
            @Override
            public void onFinish() {
                SophixStubApplication.needReboot = true;
            }
        };
    }

    /**
     * 设置状态栏是否全屏
     * @param isFull         true：全屏；false：非全屏
     * @param isUIBlack       true：图标文字为深色；false：图标文字为亮色
     * @param backgroundColor 状态栏背景色 R.color.xxx
     */
    public void setStatusBar(boolean isFull, boolean isUIBlack, int backgroundColor) {
        /*设置状态栏*/
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            View decorView = getWindow().getDecorView();
            int vis;
            //View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR：设置状态栏中的文字颜色和图标颜色为深色，不设置默认为白色，需要android系统6.0以上。
            if (isFull) {
                if (isUIBlack) {
                    vis = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
                } else {
                    vis = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_VISIBLE;
                }
            } else {
                if (isUIBlack) {
                    vis = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
                } else {
                    vis = View.SYSTEM_UI_FLAG_VISIBLE;
                }
            }
            decorView.setSystemUiVisibility(vis);
            if (backgroundColor != 0) {
                //设置状态栏规定的颜色
                getWindow().setStatusBarColor(getResources().getColor(backgroundColor));
            } else {
                //设置状态栏的默认背景颜色为白色
                getWindow().setStatusBarColor(getResources().getColor(R.color.white));
            }
        }
    }

    /**
     * 说明：判断是否需要重启设备，以此来更新系统版本
     */
    private synchronized void showDialog() {
        if (SophixStubApplication.needReboot) {
            SophixStubApplication.needReboot = false;
            new Handler(Looper.getMainLooper()).post(() -> {
                tipDialog = new GlobalDialog.Builder(BaseActivity.this)
                        .setContent("系统新版本更新完毕，重启设备生效！")
                        .setConfirmText("立即重启")
                        .setCancelText("稍后重启")
                        .setConfirmGradient(true)
                        .setOnConfirmClickListener((mGlobalDialog, v) -> reboot(BaseActivity.this.getApplicationContext()))
                        .setOnCancelClickListener((mGlobalDialog, v) -> {
                            if (dayCountTimer != null) {
                                dayCountTimer.cancel();
                                dayCountTimer.start();
                            }
                        }).show();
                if (countDownTimer != null) {
                    countDownTimer.cancel();
                    countDownTimer.start();
                }
            });
        }
    }

    public void reboot(Context context) {
        LogUtils.i("reboot");
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        if (pm != null) {
            pm.reboot("");
        }
    }

    private synchronized void checkUpdate() {
        //初始化UpdateCountTimer
        //检查系统更新倒计时
        LogUtils.i("检查一次系统更新");
        SophixManager.getInstance().queryAndLoadNewPatch();
        UpdateCountTimer updateCountTimerView = UpdateCountTimer.getInstance(BaseActivity.this);
        updateCountTimerView.start();
    }

    public void startAct(Context packageContext, Class<?> cls) {
        startAct(packageContext, cls, 0, null, R.anim.translate_in, 0);
    }

    public void startAct(Context packageContext, Class<?> cls, int RESULT_CODE) {
        startAct(packageContext, cls, RESULT_CODE, null, R.anim.translate_in, 0);
    }

    public void startAct(Context packageContext, Class<?>
            cls, Map<String, Object> map) {
        startAct(packageContext, cls, 0, map, R.anim.translate_in, 0);
    }

    public void startAct(Context packageContext, Class<?> cls, int RESULT_CODE,
                         Map<String, Object> map) {
        startAct(packageContext, cls, RESULT_CODE, map, R.anim.translate_in, 0);
    }

    public void startAct(Context packageContext, Class<?> cls, int RESULT_CODE,
                         Map<String, Object> map, int enterAnim) {
        startAct(packageContext, cls, RESULT_CODE, map, enterAnim, 0);
    }

    /**
     * 跳转activity
     * 注：跳转默认动画，从下往上进入Activity
     *
     * @param packageContext 不解释
     * @param cls            目标activity类
     * @param RESULT_CODE    跳转返回code
     * @param map            参数map集合
     * @param enterAnim      打开activity动画
     * @param exitAnim       关闭activity动画
     */
    public void startAct(Context packageContext, Class<?> cls, int RESULT_CODE,
                         Map<String, Object> map, int enterAnim, int exitAnim) {
        Intent intent = new Intent(packageContext, cls);
        //循环添加参数
        if (map != null) {
            for (String k : map.keySet()) {
                if (map.get(k) instanceof Boolean) {
                    intent.putExtra(k, (boolean) map.get(k));
                } else if (map.get(k) instanceof Byte) {
                    intent.putExtra(k, (byte) map.get(k));
                } else if (map.get(k) instanceof String) {
                    intent.putExtra(k, (String) map.get(k));
                } else if (map.get(k) instanceof Integer) {
                    intent.putExtra(k, (int) map.get(k));
                } else if (map.get(k) instanceof Long) {
                    intent.putExtra(k, (long) map.get(k));
                } else if (map.get(k) instanceof Double) {
                    intent.putExtra(k, (double) map.get(k));
                } else if (map.get(k) instanceof Float) {
                    intent.putExtra(k, (float) map.get(k));
                } else if (map.get(k) instanceof Serializable) {
                    intent.putExtra(k, (Serializable) map.get(k));
                }
            }
        }
        //设置回调
        if (RESULT_CODE == 0) {
            AppManager.getAppManager().currentActivity().startActivity(intent);
        } else {
            AppManager.getAppManager().currentActivity().startActivityForResult(intent, RESULT_CODE);
        }
        //自定义跳转动画
//        if (enterAnim != 0 || exitAnim != 0) {
//            overridePendingTransition(enterAnim, exitAnim);
//        } else {
//            overridePendingTransition(R.anim.alpha_in, 0);
//        }
    }

    public void startAct(Intent intent) {
        startAct(intent, 0, R.anim.translate_in, 0);
    }

    public void startAct(Intent intent, int RESULT_CODE) {
        startAct(intent, RESULT_CODE, R.anim.translate_in, 0);
    }

    public void startAct(Intent intent, int enterAnim, int exitAnim) {
        startAct(intent, 0, enterAnim, exitAnim);
    }

    /**
     * 跳转activity
     * 注：跳转默认动画，从下往上进入Activity
     *
     * @param intent      intent参数
     * @param RESULT_CODE 回调参数
     * @param enterAnim   进入动画
     * @param exitAnim    退出动画
     */
    public void startAct(Intent intent, int RESULT_CODE, int enterAnim, int exitAnim) {
        //设置回调
        if (RESULT_CODE == 0) {
            AppManager.getAppManager().currentActivity().startActivity(intent);
        } else {
            AppManager.getAppManager().currentActivity().startActivityForResult(intent, RESULT_CODE);
        }
        //自定义跳转动画
//        if (enterAnim != 0 || exitAnim != 0) {
//            overridePendingTransition(enterAnim, exitAnim);
//        } else {
//            overridePendingTransition(R.anim.alpha_in, 0);
//        }
    }

//    @Override
//    public void finishAct() {
//        finishAct(R.anim.translate_out);
//    }

    /*@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 点击手机上的返回键，返回上一层
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            // 移除Activity
            ActivityCollector.removeActivity(this);
            finish();
//            finishAct(R.anim.translate_out);
        }
        return true;
    }*/

    /**
     * 权限检查方法，false代表没有该权限，ture代表有该权限
     */
    public boolean hasPermission(String... permissions) {
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    /**
     * 权限请求方法
     */
    public void requestPermission(int code, String... permissions) {
        ActivityCompat.requestPermissions(this, permissions, code);
    }

    /**
     * 处理请求权限结果事件
     *
     * @param requestCode  请求码
     * @param permissions  权限组
     * @param grantResults 结果集
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        doRequestPermissionsResult(requestCode, grantResults);
    }

    /**
     * 处理请求权限结果事件
     *
     * @param requestCode  请求码
     * @param grantResults 结果集
     */
    public void doRequestPermissionsResult(int requestCode, @NonNull int[] grantResults) {
    }

    /**
     * 主要的方法，重写dispatchTouchEvent
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
//        switch (ev.getAction()) {
//            //获取触摸动作，如果ACTION_UP，计时开始。
//            case MotionEvent.ACTION_UP:
//                if (ScreenProtectConstant.time != ScreenProtectConstant.NEVER) {
//                    CountTimer.restart(BaseActivity.this.getApplicationContext());
//                }
//                break;
//        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    protected void onStart() {
        super.onStart();
//        if (this instanceof MainActivity) {
//            LogUtils.d("行为统计，进入主菜单页面");
//            AppCollectUtil.getInstance().activityDataCollect(this.toString(), null, null, true, this, 1);
//        }
    }

    @Override
    protected void onStop() {
        super.onStop();
//        if (this instanceof MainActivity) {
//            LogUtils.d("行为统计，退出主菜单页面");
//            AppCollectUtil.getInstance().activityDataCollect(this.toString(), null, null, false, this, 2);
//        }
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        showDialog();
    }

    @Override
    protected void onDestroy() {
        // Activity销毁时，提示系统回收
        System.gc();
        // 移除Activity
        ActivityCollector.removeActivity(this);
        super.onDestroy();
        /*if (mScreenOffReceiver != null) {
            try {
                unregisterReceiver(mScreenOffReceiver);
            } catch (IllegalArgumentException e) {
                //LogUtils.e("捕捉一个crash：Receiver not registered: mScreenOffReceiver");
            }
        }*/
    }
}
